from django.contrib.auth.mixins import LoginRequiredMixin
from django.views import View
from django.conf import settings
from itsdangerous import TimedJSONWebSignatureSerializer as TJSS
from users.models import User

class MyLoginRequiredMiXinView(LoginRequiredMixin,View):
    login_url = '/login/'


# 签名加密
def generate_verify_url(user):
    # 生成数据信息
    data = {"user_id": user.id, "email": user.email}

    # 创建对象
    serializer = TJSS(secret_key=settings.SECRET_KEY, expires_in=60*15)

    # 生成token
    # dumps( Like :meth:`.Serializer.dumps` but creates a JSON WebSignature.)
    token = serializer.dumps(data).decode()

    # 返回结果
    verify_url = "%s?token=%s" % (settings.EMAIL_VERIFY_URL, token)
    return verify_url

# 签名解密
def decode_verify_url(token):

    # 创建对象
    serializer = TJSS(secret_key=settings.SECRET_KEY, expires_in=60 * 15)

    # 解密
    try:
        data_dict = serializer.loads(token)
        user_id = data_dict.get("user_id")

        user = User.objects.get(id=user_id)
    except:
        return None

    # 返回结果
    return user

